package com.fowo.api.datainterface.service.impl.implCore;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.constants.RequestMethodKind;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.service.serviceCore.BaseInvokeService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.JScriptUtil;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.walmart.util.WalmartUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
@DS("ds24")
@RequiredArgsConstructor
public class WalmartServiceImpl  implements BaseInvokeService {

    private final Common common;

    private volatile BaseAspect baseAspect;

    private final JScriptUtil jScriptUtil;

    public synchronized BaseAspect getBaseAspect(String type) {
        return ObjUtil.isEmpty(baseAspect) ? new BaseAspect(type) : baseAspect;
    }

    @Override
    public DataTypeKind getType() {
        return DataTypeKind.WALMART;
    }

    @Override
    public Object getAuth(DataContextModel.DatainterfaceAuthorityModel invoke) {
        return null;
    }

    @Override
    public Object invoke(DataContextModel.DatainterfaceInvokeModel invoke, Object currentParamsMap, JSONObject currentHeadersMap) {
        JSONObject jsonObject = null;
        HttpHeaders header = new HttpHeaders();
        // 请求地址
        String path =  URLUtil.toUrlForHttp(StrUtil.concat(true,invoke.getAuthority().getRootPath(),invoke.getInterfaceUrl())).toString();
        // 请求方法
        HttpMethod requestMethod = common.convertRequestMethod(invoke.getRequestMethod());
        // 获取请求参数
        JSONObject requestParams = JsonUtil.getJsonToBeanSafe(currentParamsMap,JSONObject.class);

        if (HttpUtil.isHttp(path) || HttpUtil.isHttps(path)) {
            if(currentParamsMap!=null&& StringUtils.hasText(requestParams.getString("path"))){
                path= String.format(path,requestParams.getString("path"));
                requestParams.remove("path");
            }
            if (StrUtil.equalsIgnoreCase(RequestMethodKind.Get.getValue(), requestMethod.name())) {
                if(requestParams.getString("next") != null){
                    path = path + requestParams.getString("next");
                }else {
                    path = common.processUrlArgs(requestParams, path, null);
                }
            } else if (StrUtil.equalsIgnoreCase(RequestMethodKind.Post.getValue(), requestMethod.name()) ||
                    StrUtil.equalsIgnoreCase(RequestMethodKind.Put.getValue(), requestMethod.name()) ||
                    StrUtil.equalsIgnoreCase(RequestMethodKind.Delete.getValue(), requestMethod.name())) {
                jsonObject = common.processBodyArgs(requestParams, jsonObject, null);
            } else {
                Assert.isTrue(false, "接口 {} ，指定的查询类型 {} 错误 ！", invoke.getEnCode(), requestMethod.name());
            }

            for (String field : currentHeadersMap.keySet()) {
                header.set(field, currentHeadersMap.getString(field));
            }
            Object res;
            try {
                res = getBaseAspect(invoke.getAuthority().getAppName()).httpRequest(path, requestMethod, jsonObject, header,String.class, Constants.Read,StrUtil.EMPTY);
            } catch (Exception ex) {
                throw new RuntimeException(StrUtil.format("API 接口 {} ，执行 {} 操作 {} 发生异常 ",  invoke.getEnCode(), path, StrUtil.subPre(JsonUtil.getObjectToString(currentParamsMap), 500), ExceptionUtil.getRootCauseMessage(ex)));
            }
            if (ObjectUtil.isEmpty(res)) {
                throw new RuntimeException(StrUtil.concat(true, "拉取失败或无返回值：", StrUtil.subPre(JsonUtil.getObjectToString(res), 500)));
            }
            return jScriptUtil.callJsInvoke(invoke.getDataProcessing(), res == null ? new ArrayList<>() : res, null, null);
        } else {
            Assert.isTrue(false, "接口 {} ，地址 {} 错误 ！", invoke.getEnCode(), path);
        }
        return null;
    }
}
